package mysql_jdbc;

import com.mysql.jdbc.Driver;
import java.sql.*;

public class Connect {
    
    public enum WordType {
        WT_PERSON(1), WT_ORGANIZATION(2), WT_LOCATION(3), WT_UNKNOWN(4);
    
        private int code;
 
        private WordType(int c) {
            code = c;
        }

        public int getCode() {
            return code;
        }
    };

    /**
     * @param host_name MySQL host name.
     * @param db_name Database name, which contains info about Person, Organization, Location.
     * @param user_name DB user name.
     * @param password User password.
     * @throws SQLException 
     */
    public Connect(String host_name, String db_name, String user_name, String password) throws SQLException{
        makeConnection(host_name, db_name, user_name, password);
    } 

    private Connection conn;  
    private int MAX_TYPE_VALUE = 3;

    /**
     * @param host_name MySQL host name.
     * @param db_name Database name, which contains info about Person, Organization, Location.
     * @param user_name DB user name.
     * @param password User password.
     * @throws SQLException 
     */
    public  Connection makeConnection(String host_name, String db_name, String user_name, String password) throws SQLException {
        if (conn == null) {
            new Driver();
            conn = DriverManager.getConnection("jdbc:mysql://"+host_name+"/"+db_name, user_name, password);
        }

        return conn;
    }  

    /**
     * 
     * @param word
     * @return Word type: Person, Organization, Location or Unknown.
     * @throws SQLException 
     */
    
    public WordType GetWordType(String word) throws SQLException {
        PreparedStatement prest;
        prest = conn.prepareStatement("SELECT TypeId FROM ProperNames WHERE ProperName = '" + word + "'");

        ResultSet rs1 = prest.executeQuery();
        
        if (!rs1.isBeforeFirst())
            return WordType.WT_UNKNOWN;
        
        rs1.next();
        int TypeId = rs1.getInt(1);  
        
        switch (TypeId) {
            case 1: return WordType.WT_PERSON;
            case 2: return WordType.WT_ORGANIZATION;
            case 3: return WordType.WT_LOCATION;
            default: return WordType.WT_UNKNOWN;
        }
    }
}
